package com.nile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author: zhang kai
 * @Date: 2022/06/16
 * @Description:
 */
public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
        RandomAccessFile f = null;
        FileChannel c = null;
        try {
            f = new RandomAccessFile("data.txt", "rw");
            //获取Channel
            c = f.getChannel();
            //channel是基于缓冲区读写到
            //创建缓冲区，将文件数据写入缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (c.read(buffer) != -1) {
                //读取流需要进行翻转
                //limit = position,position = 0，可以读取写入到数据
                buffer.flip();
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }
                buffer.clear();

                buffer.reset();
            }
        } finally {
            c.close();
            f.close();
        }
    }
}
